package com.csx.micrometer.invoke.context.webflux;

import cn.hutool.core.collection.CollectionUtil;
import com.csx.micrometer.invoke.context.MicrometerMessage;
import com.csx.micrometer.invoke.context.MicrometerRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;

import java.util.*;

/**
 * @author cuisongxu
 * @date 2023/2/9 9:48
 */
public class MicrometerWebFluxRequest extends MicrometerRequest {

    public MicrometerWebFluxRequest(ServerWebExchange originRequest) {
        super(originRequest);
    }

    @Override
    public List<String> getHeaders(String name) {
        List<String> headers = getOriginRequest().getHeaders().get(name);
        if(CollectionUtil.isEmpty(headers)) {
            return new ArrayList<>();
        }
        return headers;
    }

    @Override
    public Map<String, String> getSingleValueHeaders() {
        HttpHeaders httpHeaders = getOriginRequest().getHeaders();
        Map<String, String> headers = new HashMap<>();

        for (Map.Entry<String, List<String>> entry : httpHeaders.entrySet()) {
            String headerName = entry.getKey();
            List<String> headerValues = entry.getValue();
            if(CollectionUtil.isEmpty(headerValues)) {
                continue;
            }
            headers.put(headerName, headerValues.get(0));
        }
        return headers;
    }

    @Override
    public String getFirstHeader(String name) {
        List<String> headerValues = getOriginRequest().getHeaders().get(name);
        if(CollectionUtil.isEmpty(headerValues)) {
           return null;
        }
        return headerValues.get(0);
    }

    @Override
    public ServerHttpRequest getOriginRequest() {
        return ((ServerWebExchange)super.getOriginRequest()).getRequest();
    }

    @Override
    public Object getAttribute(String key) {
        return ((ServerWebExchange)super.getOriginRequest()).getAttribute(key);
    }

    @Override
    public MicrometerMessage setAttribute(String key, Object value) {
        return super.setAttribute(key, value);
    }

    @Override
    public void removeAttribute(String key) {
        super.removeAttribute(key);
    }

    @Override
    public Map<String, Object> getAttributes() {
        ServerWebExchange originRequest = (ServerWebExchange) super.getOriginRequest();
        Map<String, Object> attributes = originRequest.getAttributes();
        return attributes;
    }

    @Override
    public String getRequestURL() {
        return getOriginRequest().getURI().toString();
    }

    @Override
    public String getRequestURI() {
        return getOriginRequest().getPath().toString();
    }

    @Override
    public String getMethod() {
        return Objects.requireNonNull(getOriginRequest().getMethod()).toString();
    }
}
